<?php
namespace app\lib\template;
use app\api\model\template\Send;
use app\lib\wechat\WXBizMsgCrypt;
use think\facade\Log;
use think\facade\Request;
define("TOKEN", "weixin");
class Template
{
    //服务商
    protected static $appid = 'wx22c04bcd80855802';
    protected static $appsecret = '32d5021fd4227b292a94e851d1c83e0c';
    protected static $EncodingAESKey = 'ZJrRTXBb9unPMqBjvm8JSb6qM0SbCWXOezr2l51n5Uv';

    public function template_list(){
      $content = new Content();
      return $content->template();
    }

    public function user_tag(){
        $usertag = new UserTag();
        return $usertag->usertag();
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            return $echoStr;
        }else{
            return false;
        }
    }
    public function responseMsg()
    {
//get post data, May be due to the different environments
        $postStr =  file_get_contents('php://input');
//        Log::write('postStr'.print_r($postStr,true));
//        if (!empty($postStr)){
//            //解密
//            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//            Log::write('postObj'.print_r($postObj,true));
//            return $postObj;
//        }else {
//            return false;
//        }



        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $msg_signature = $_GET["msg_signature"];
        $nonce = $_GET["nonce"];
        $encryptMsg = '';
        $pc = new WXBizMsgCrypt(TOKEN,self::$EncodingAESKey,self::$appid);
        //extract post data
        if (!empty($postStr)){
            //解密
            $msg = '';
            $errCode = $pc->decryptMsg($msg_signature,$timestamp,$nonce,$postStr,$msg);
            if ($errCode !=0){
                return false;
            }
            $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
            return $postObj;
        }else {
            return false;
        }
    }
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function getAccessToken(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.self::$appid.'&secret='.self::$appsecret;
        $res = $this->request_get($url);
        $result = \GuzzleHttp\json_decode($res, true)['access_token'] ?? '';
        if (empty($result)){
            $send_arr = [
                "openid"=>'',
                "template_id"=>'',
                "content"=>print_r($res,true),
                "errcode"=>'',
                "errmsg"=>''
            ];
            Send::create($send_arr);
        }
        return $result;
    }
    //用户基础信息
    public function getUser($access_token='',$openid=''){
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        return $this->request_get($url);
    }

    //打标用户列表
    public function getTagUser($access_token='', $tag_id, $openid=''){
        $param = array(
            'tagid' => $tag_id,
            'next_openid' => $openid
        );
        $json_param = json_encode($param);
        $url = 'https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token='.$access_token.'&lang=zh_CN';
        $dataRes = $this->request_post($url, urldecode($json_param))??[];
        $dataRes = json_decode($dataRes,true);
        return $dataRes;
    }

    public function doSend($touser,$template_id,$url,$data,$accessToken,$miniprogram =[],$topcolor = '#7B68EE')
    {

        /*
        * data=>array(
        'first'=>array('value'=>urlencode("您好,您已购买成功"),'color'=>"#743A3A"),
        'name'=>array('value'=>urlencode("商品信息:微时代电影票"),'color'=>'#EEEEEE'),
        'remark'=>array('value'=>urlencode('永久有效!密码为:1231313'),'color'=>'#FFFFFF'),
        )
        */
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'miniprogram'=>$miniprogram,
//            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;
        $dataRes = $this->request_post($url, urldecode($json_template))??[];
        $dataRes = json_decode($dataRes,true);
        return $dataRes;
    }

    public function AllTemplate($access_token = ""){
        $url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=".$access_token;
        $result = $this->request_get($url);
        return \GuzzleHttp\json_decode($result, true) ?? [];
    }

    /**
     * 发送post请求
     */
    private function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;

    }

    /**
     * 发送get请求
     */
    private function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
